package com.fengxu.gamescript.data;

import android.content.Context;
import android.util.ArraySet;

import com.alibaba.fastjson.JSON;
import com.fengxu.gamescript.data.other.YsKeyConf;
import com.fengxu.gamescript.data.vo.ExistScript;
import com.fengxu.gamescript.util.CommonUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * 全局配置类
 */
public class Conf {

    // 配置文件名
    private static final String ConfFileName = "conf.json";

    // 单例
    private static volatile Conf instance;

    // 悬浮窗设置改变
    private Consumer<Boolean> flowSettingChanged;

    // 设置悬浮窗设置改变事件
    public void setFlowSettingChanged(Consumer<Boolean> flowSettingChanged) {
        this.flowSettingChanged = flowSettingChanged;
    }

    // 历史记录改变
    private Consumer<List<String>> searchHistoryChanged;

    // 设置搜索历史改变事件
    public void setSearchHistoryChanged(Consumer<List<String>> searchHistoryChanged) {
        this.searchHistoryChanged = searchHistoryChanged;
    }

    /*************  下方配置项  **************/

    // 用户邮箱
    private String email;

    // 用户密码
    private String pwd;

    // 是否开启悬浮窗
    private boolean isStartFlowWin;

    // 用户云脚本搜索历史
    private List<String> scriptSearchHistory = new ArrayList<>();

    // 用户已经下载的云脚本
    private List<ExistScript> existScriptList = new ArrayList<>();

    // 用户原神键位配置
    @Deprecated
    private YsKeyConf ysKeyConf = new YsKeyConf();

    private Conf(){}

    /**
     * 获取全局配置
     * @param ctx  上下文对象
     */
    public synchronized static void initConf(Context ctx){
        if(instance == null){
            instance = readConf(ctx);
        }
    }

    /**
     * 获取全局配置
     * @return  全局配置
     */
    public synchronized static Conf getConf(){
        if(instance == null){
            throw new RuntimeException("还未初始化配置");
        }
        return instance;
    }

    /**
     * 从配置文件中读取配置
     * @param ctx   上下文对象
     * @return  配置对象
     */
    private static Conf readConf(Context ctx){
        Conf conf = null;
        try {
            FileInputStream fis = ctx.openFileInput(ConfFileName);
            String json = CommonUtils.INSTANCE.readInputStream(fis);
            conf = JSON.parseObject(json,Conf.class);
            fis.close();
        } catch (FileNotFoundException e) {
            conf = new Conf();
        }catch (Exception e){
            e.printStackTrace();
        }
        return conf;
    }

    /**
     * 保存配置至文件中
     * @param ctx 上下文对象
     */
    public synchronized static void saveConf(Context ctx){
        if(instance == null){
            throw new RuntimeException("未初始化配置");
        }
        try {
            FileOutputStream fos = ctx.openFileOutput(ConfFileName, Context.MODE_PRIVATE);
            String json = JSON.toJSONString(instance);
            fos.write(json.getBytes());
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public boolean isStartFlowWin() {
        return isStartFlowWin;
    }

    @Deprecated
    public YsKeyConf getYsKeyConf() {
        return ysKeyConf;
    }

    @Deprecated
    public void setYsKeyConf(YsKeyConf ysKeyConf) {
        this.ysKeyConf = ysKeyConf;
    }

    public void setStartFlowWin(boolean startFlowWin) {
        isStartFlowWin = startFlowWin;
        if(flowSettingChanged != null){
            flowSettingChanged.accept(startFlowWin);
        }
    }

    // 返回一个不可修改的列表
    public List<String> getScriptSearchHistory() {
        return Collections.unmodifiableList(scriptSearchHistory);
    }

    // 设置搜索历史
    public void setScriptSearchHistory(List<String> scriptSearchHistory) {
        this.scriptSearchHistory = scriptSearchHistory;
        if(searchHistoryChanged != null){
            searchHistoryChanged.accept(scriptSearchHistory);
        }
    }

    // 添加一个搜索记录
    public void addSearchHistory(String text){
        if(!scriptSearchHistory.contains(text)){
            scriptSearchHistory.add(text);
        }
        if(searchHistoryChanged != null){
            searchHistoryChanged.accept(getScriptSearchHistory());
        }
    }

    // 移除一个搜索记录
    public void removeSearchHistory(String text){
        scriptSearchHistory.remove(text);
        if(searchHistoryChanged != null){
            searchHistoryChanged.accept(getScriptSearchHistory());
        }
    }

    // 移除所有搜索记录
    public void removeAllSearchHistory(){
        scriptSearchHistory.clear();
        if(searchHistoryChanged != null){
            searchHistoryChanged.accept(getScriptSearchHistory());
        }
    }


    public List<ExistScript> getExistScriptList() {
        return existScriptList;
    }

    public void setExistScriptList(List<ExistScript> existScriptList) {
        this.existScriptList = existScriptList;
    }

    /**
     * 清除掉已下载脚本中不存在(被删除)的脚本
     */
    public void clearNotExistScript(){
        Iterator<ExistScript> iterator = existScriptList.iterator();
        while (iterator.hasNext()){
            ExistScript script = iterator.next();
            if(!new File(script.getExistPath()).exists()){
                iterator.remove();
            }
        }
    }
}
